package main

import (
	"fmt"
	"os"
	"path/filepath"
	"peilian-api/app/global/databases/tables"
	"peilian-api/utils/encrypt"
	"strings"
	"time"

	"github.com/tealeg/xlsx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// // 学历是固定的，无需加入数据库
// var EducationArr = []string{"大专", "本科", "硕士", "博士"}
//
// // 年级固定
// var GradeArr = []string{"2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023"}
//
// var AgentId = 45
// var InserSchool = "厦门大学"

var SchoolConstituteId int

var db *gorm.DB
var err error

const (
	userName = "youshi"
	pwd      = "1G?ywxyrlis4Orl"
	ipCode   = "10.9.93.161:3306"
	dbName   = "peilian"
)

// const (
// 	userName = "youshi_t"
// 	pwd      = "2K4adice?sdfrx3e"
// 	ipCode   = "10.9.93.161:3306"
// 	dbName   = "peilian_test_zs"
// )

func generatePwd(sno string) string {
	// 1. 根据学校名称获取学校前缀
	var prefix = "xm"
	// 2. 生成密码
	// rsaPwd, _ := encrypt.RsaEncode(prefix + sno)
	pwd, _ := encrypt.EncryptPassword(prefix + sno)
	return pwd
}

func CreateDB() error {
	dbinfo := strings.Join([]string{userName, ":", pwd, "@tcp(", ipCode, ")/", dbName, "?charset=utf8&parseTime=True&loc=Local"}, "")
	db, err = gorm.Open(mysql.Open(dbinfo), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return err
	}
	return nil
}

func ReadExcle(filepath string) [][][]string {
	out, err := xlsx.FileToSlice(filepath)
	if err != nil {
		panic(err.Error())
	}
	return out
}
func Contains(elements []string, needle string) bool {
	for _, v := range elements {
		if needle == v {
			return true
		}
	}

	return false
}

type Model struct {
	Id        uint           `gorm:"primarykey" json:"id"`
	CreatedAt time.Time      `json:"created_at" format:"2006-01-02 15:04:05"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

type Constitute struct {
	Model
	Type       string `json:"type"`
	Name       string `json:"name"`
	BelongToId int    `json:"belong_to_id"`
	AgentId    int    `json:"agent_id"`
}

var m map[string]int = make(map[string]int, 0)
var q map[string]map[string]int = make(map[string]map[string]int, 0)

func dealMap() {
	var c []Constitute
	db.Table("constitute").Where("type = ? and belong_to_id = ?", "academy", SchoolConstituteId).Select("id,name,type,belong_to_id").Find(&c)
	for i := 0; i < len(c); i++ {
		m[c[i].Name] = int(c[i].Id)
		if _, ok := q[c[i].Name]; !ok {
			q[c[i].Name] = make(map[string]int, 0)
		}
		var d []Constitute
		db.Table("constitute").Where("type = ? and belong_to_id = ?", "profession", c[i].Id).Select("id,name,type,belong_to_id").Find(&d)
		for j := 0; j < len(d); j++ {
			q[c[i].Name][d[j].Name] = int(d[j].Id)
		}
	}
}

func main() {
	CreateDB()
	dir, _ := os.Getwd()
	filePath := dir + "/scripts/school/renda/宁波职业技术学院.xlsx"
	schoolName := strings.Split(filepath.Base(filePath), ".")[0]
	// 获取id
	var constitute tables.Constitute
	db.Table("constitute").Where("name = ?", schoolName).Select("id,name").Find(&constitute)
	if constitute.ID != 0 {
		SchoolConstituteId = int(constitute.ID)
	}
	fmt.Printf("SchoolConstituteId:%d", SchoolConstituteId)
	if SchoolConstituteId == 0 {
		return
	}
	var insertNum int

	s := ReadExcle(filePath)
	// 做个学院和id的映射关系
	var mapping = map[string]int{}
	mapping = make(map[string]int, 0)
	for i := 0; i < len(s); i++ {
		for j := 0; j < len(s[i]); j++ {
			if s[i][j][0] == "所在院系" {
				continue
			}
			if len(s[i][j][0]) != 0 {
				// 先查询是否存在
				var d Constitute
				db.Table("constitute").Where("type = ? and belong_to_id = ? and name = ?", "academy", SchoolConstituteId, s[i][j][0]).Select("id,name,type,belong_to_id").Find(&d)
				if d.Id != 0 {
					mapping[s[i][j][0]] = int(d.Id)
				} else {
					c := Constitute{Name: s[i][j][0], Type: "academy", BelongToId: SchoolConstituteId}
					db.Table("constitute").Create(&c)
					mapping[s[i][j][0]] = int(c.Id)
				}

			}
			if len(s[i][j][0]) > 0 && len(s[i][j][1]) > 0 {
				// 插入专业
				if _, ok := mapping[s[i][j][0]]; !ok {
					continue
				}
				belongId := mapping[s[i][j][0]]
				var d Constitute
				db.Table("constitute").Where("type = ? and belong_to_id = ? and name = ?", "profession", belongId, s[i][j][1]).Select("id,name,type,belong_to_id").Find(&d)
				if d.Id != 0 {
					continue
				} else {
					c := Constitute{Name: s[i][j][1], Type: "profession", BelongToId: belongId}
					db.Table("constitute").Create(&c)
					insertNum++
				}
			}

		}
	}
	fmt.Printf("inser nums %d", insertNum)
}
